package com.pruebas;

import java.io.StringReader;
import java.io.StringWriter;

import org.supercsv.cellprocessor.ConvertNullTo;
import org.supercsv.cellprocessor.ParseInt;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.prefs.CsvPreference;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		try {
			should_partial_read();
			should_partial_write();
			
		} catch (Exception e) {
			 System.out.print("Error: " + e.getMessage());
		}

	}
	
	public static void should_partial_read() throws Exception {
	    // content of a file containing orders and product numbers
	    String fileData = "orderNumber, productNumber\n1,22";

	    // setup conversion from String to integers (as our fields are type int)
	    CellProcessor[] processing = new CellProcessor[] { new ParseInt(), new ParseInt() };

	    // the actual reading
	    CsvBeanReader reader = new CsvBeanReader(new StringReader(fileData), CsvPreference.EXCEL_PREFERENCE);
	    // get header to identify what fields to populate
	    String[] header = reader.getCSVHeader(true);
	    Order order = reader.read(Order.class, header, processing);

	    // show that only part of the object has been populated with values
	    System.out.print("order: " + order.getOrderNumber()
	            + " product: " + order.getProductNumber()
	            + " parent: " + order.getParentOrder() + "\n**\n");
	}
	
	public static void should_partial_write() throws Exception {
	    // The data to write
	    Order mainOrder = new Order();
	    mainOrder.setOrderNumber(1);
	    mainOrder.setProductNumber(42);
	    mainOrder.setUserComment("some comment");
	    Order subOorder = new Order();
	    subOorder.setOrderNumber(2);
	    subOorder.setParentOrder(1);
	    subOorder.setProductNumber(43);

	    // for testing write to a string rather than a file
	    StringWriter outFile = new StringWriter();

	    // setup header for the file and processors. Notice the match between the header and the attributes of the
	    // objects to write. The rules are that
	    // - if optional "parent orders" are absent, write -1
	    // - and optional user comments absent are written as ""
	    String[] header = new String[] { "orderNumber", "parentOrder", "productNumber", "userComment" };
	    CellProcessor[] Processing = new CellProcessor[] { null, new ConvertNullTo(-1), null, new ConvertNullTo("\"\"") };

	    // write the partial data
	    CsvBeanWriter writer = new CsvBeanWriter(outFile, CsvPreference.EXCEL_PREFERENCE);
	    writer.writeHeader(header);
	    writer.write(mainOrder, header, Processing);
	    writer.write(subOorder, header, Processing);
	    writer.close();

	    // show output
	    System.out.println(outFile.toString());
	}

}
